/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package by.vdl.websort.controllers;

import by.vdl.websort.server.entity.UserDTO;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;

import javax.servlet.http.HttpSession;

/**
 *
 * @author vasilenko
 */
@Controller
@RequestMapping(value="/auth")
@SessionAttributes({"isAuth", "userDTO"})
public class AuthController extends AbstractController{
    
    
    
    
    
    @RequestMapping(value="/notLogged", method = RequestMethod.GET)
    protected String noLogin(HttpSession session) throws Exception {
        Boolean isAuth = (Boolean)session.getAttribute("isAuth");
        if(isAuth!=null && isAuth){
            return "redirect:/indexPage";
        }else {
            return "auth/loginPage";
        }
    }
    
    @RequestMapping(value="/login", method = RequestMethod.POST)
    protected String login(@RequestParam(required = true) String userName, @RequestParam(required = true) String userPassword, ModelMap modelMap) throws Exception {
        UserDTO assertUser = getCommonDao().getUserDao().checkUser(userName, userPassword);       
        if(assertUser != null){
            modelMap.addAttribute("isAuth",true);
            modelMap.addAttribute("userDTO", assertUser);
            return "redirect:/index";
        } else{
            modelMap.addAttribute("isAuth",false);
            return "redirect:/auth/notLogged";
        }
    }
    //Use onSubmit instead of doSubmitAction 
    //when you need access to the Request, Response, or BindException objects
    /*
     * @Override protected ModelAndView onSubmit( HttpServletRequest request,
     * HttpServletResponse response, Object command, BindException errors)
     * throws Exception { ModelAndView mv = new ModelAndView(getSuccessView());
     * //Do something... return mv; }
     */
}
